var iot = require('iot');
var network = require('network');

var iotdev;

// const productkey = 'a1f1iRQKtio';
// const devicename = 'test_d01';
// const devicesecret = '95b83581f32d7c297ffc318ae24c913a';


const productkey = 'a1iqVkRKyR8';
const devicename = '867567041091141';
const devicesecret = '2bb244253697a178f6bfe273224f6e67';
const LightSwitch_cjson='{"LightSwitch":1}';
var lightSwitch = 0;

var errCode = 0;

function iotDeviceOnConnect()
{
    iotdev.onService(function(service) {
        console.log('received cloud service id ' + service.service_id);
        console.log('received cloud service param  ' + service.params);
        console.log('received cloud service param len  ' + service.params_len);
    });

    iotdev.onProps(function(properity) {
        console.log('received cloud properity param ' + properity.params);
        console.log('received cloud properity param len ' + properity.params_len);
    });


}
setInterval(function() {
    lightSwitch = 1 - lightSwitch;
    //console.log('post lightSwitch1 ' + JSON.stringify({LightSwitch: lightSwitch}));

    // Post properity
    iotdev.postProps(
        JSON.stringify({
            LightSwitch: lightSwitch
        })
    );
    console.log('post lightSwitch zhangyang' + lightSwitch + ', ErrorCode ' + errCode);
    errCode++;
    //Post properity
    // iotdev.postProps(LightSwitch_cjson);

    // //Post event
    // iotdev.postEvent({
    //     id: 'ErrorMessage',
    //     params: JSON.stringify({
    //         ErrorCode: errCode
    //     })
    // });

   
},500);
function iotDeviceCreate()
{
    iotdev = iot.device({
        productKey: productkey,
        deviceName: devicename,
        deviceSecret: devicesecret,
    });

    iotdev.on('connect', function () {
        console.log('success connect to aliyun iot server');
        iotDeviceOnConnect();
    });

    iotdev.on('reconnect', function () {
        console.log('success reconnect to aliyun iot server');
    });

    iotdev.on('disconnect', function () {
        console.log('aliyun iot server disconnected');
    });
}

var networkClient = network.openNetWorkClient();

var netStatus = networkClient.getStatus();
console.log('xxxxxxxxxxxxxxx network status ' + netStatus);
if (netStatus == 'connect') {
    console.log('network connected, create iot connection');
    iotDeviceCreate();
} else {
    networkClient.on('connect', function() {
        console.log('network connected, create iot connection');
    iotDeviceCreate();
    });
}
